<template>
  <div ref="echartDom" style="width: 100%; height: 100%"></div>
</template>

<script setup>
import {ref, reactive, onMounted, onUnmounted, watchEffect, shallowRef, inject} from "vue";
import liaoning from "@/utils/liaoning.json";
import {pxToRem} from "@/utils/index";

const chartsData = reactive({
  list: [],
  min: 0,
  max: 0,
});
const myChart = shallowRef(null);
const echartDom = ref(null);
const echarts = inject("echarts");
const currentCityCode = ref('')
// 获取地图数据
let mapData = liaoning;
// 注册自定义地图类型, 类型名称, 地图数据
echarts.registerMap("华盾", mapData);

// 接收参数
const props = defineProps({
  listData: {
    type: Array,
    default: () => [],
  },
  mapConfig: {
    type: Object,
    default: () => {
    },
  },
});
const emits = defineEmits(["mapNameChange"]);
chartsData.list = props.listData;

const initEchart = () => {
  if (echartDom.value && chartsData.list) {
    myChart.value = echarts.init(echartDom.value);
    const grid = {
      left: "0%",
      right: "0",
      bottom: "0%",
      top: "0%",
      containLabel: true,
    };
    const geo = [
      {
        map: "华盾",
        type: "map",
        aspectScale: 1,
        zoom: 1,
        layoutCenter: ["50%", "50%"],
        layoutSize: props?.mapConfig?.layoutSize || '105%',
      },
      // 重影
      {
        type: "map",
        map: "华盾",
        zlevel: -1,
        aspectScale: 1,
        zoom: 1,
        layoutCenter: ["50%", "51.3%"],
        layoutSize: props?.mapConfig?.layoutSize || '105%',
        itemStyle: {
          normal: {
            borderWidth: 2,
            borderColor: "RGBA(86, 139, 239, 1)",
            areaColor: "green",
          }
        },
      }
    ]
    const series = [
      {
        name: "华盾数据",
        type: "map",
        map: "华盾", // 自定义扩展图表类型
        selectedMode: 'single', // 只允许单选
        aspectScale: 1,
        zoom: 1, // 缩放
        select: {
          label: {
            color: 'white',
          },
          itemStyle: {
            color: 'rgb(55, 229, 245)'
          }
        },
        label: {
          normal: {
            show: true,
            textStyle: {
              color: "#fff",
              fontWeight: "bold",
              fontSize: pxToRem(12),
              fontStyle: "italic",
            },
          },
          emphasis: {
            show: true,
            textStyle: {
              color: "#fff",
            },
          },
        },
        itemStyle: {
          normal: {
            borderColor: "rgb(55, 229, 245)",
            borderWidth: 0.5,
            areaColor: "rgb(32,115,201)",
          },
          emphasis: {
            areaColor: "rgba(51, 227, 244, 0.8)",
          },
        },
        layoutCenter: ["50%", "50%"],
        layoutSize: props?.mapConfig?.layoutSize || '105%',
        data: chartsData.list,
      },
    ];
    const option = {
      grid,
      geo,
      series,
    };
    chartsData.min = Math.min(...chartsData.list.map((obj) => obj.value));
    chartsData.max = Math.max(...chartsData.list.map((obj) => obj.value));
    option.series[0].data = chartsData.list; // 更新series中的数据
    // 监听地图点击事件
    myChart.value.setOption(option);

    myChart.value.on("click", (params) => {
      if (params?.data?.select?.disabled) {
        myChart.value.dispatchAction({
          type: 'select',
          seriesIndex: 0,
          dataIndex: series[0].data.findIndex(item => item.code === props?.mapConfig?.currentCity)
        });
        ElMessage({
          showClose: true,
          message: '您无权限访问该城市数据',
          type: 'warning',
        })
        params.event.stop();
        return;
      }
      const permissionCityCode = localStorage.getItem('cityCode')
      if (params.data.code === props?.mapConfig?.currentCity && permissionCityCode !== '210000') { // 城市权限为单市且依旧点击当前已选中的城市时
        myChart.value.dispatchAction({
          type: 'select',
          seriesIndex: 0,
          dataIndex: series[0].data.findIndex(item => item.code === props?.mapConfig?.currentCity)
        });
        params.event.stop();
        return;
      }
      if (currentCityCode.value === params.data.code) {
        currentCityCode.value = ''
      } else {
        currentCityCode.value = params.data.code
      }
      emits("mapNameChange", {
        cityName: params.data.name,
        cityCode: params.data.code,
        cancelCurrentCity: !currentCityCode.value
      });
    });
  }
};

const updateChart = () => {
  if (chartsData.list.length > 0) {
    chartsData.mapInd = props.mapInd;
    if (myChart.value && !myChart.value.isDisposed()) {
      myChart.value.dispose(); // 销毁旧图表实例
    }
    initEchart();
  }
};

onMounted(() => {
  initEchart();
  window.addEventListener("resize", updateChart);
});

onUnmounted(() => {
  window.removeEventListener("resize", updateChart);
});
</script>
